package com.manager.controller;


import com.google.zxing.qrcode.encoder.QRCode;
import com.manager.bean.Account;
import com.manager.bean.QRcodeKey;
import com.manager.bean.StudentAccess;
import com.manager.service.QRcodeService;
import com.manager.service.StudentAccessService;
import com.manager.util.MD5Utils;
import com.manager.util.QRcodeUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Random;

import com.manager.util.tts;
@Controller
public class QRcodeController {
    @Resource
    private QRcodeService qRcodeService;

    @Resource
    private StudentAccessService studentAccessService;

    @RequestMapping(value = "/getQRcode",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public void getQRcode(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception {


        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        int stuId = ((Account)session.getAttribute("ad")).getAccount();

        StudentAccess studentAccess = studentAccessService.queryByStuIdDESC(stuId);
        if(studentAccess==null||studentAccess.getComeback()!=null){
            studentAccessService.insert(new StudentAccess(stuId));
        }

        QRcodeKey qRcodeKey = qRcodeService.queryById(stuId);
        BufferedImage bi = null;
        if(qRcodeKey!=null){
            if(new Date().getTime()-qRcodeKey.getCreateTime()>5*60*1000){
                qRcodeService.deleteById(stuId);
                String qrcode = MD5Utils.md5(""+stuId+new Random().nextInt(999));
                bi =  QRcodeUtils.createImage(stuId+qrcode,"",false);
                qRcodeService.insert(new QRcodeKey(stuId,qrcode,new Date().getTime()));
            }
            else{
                String qrcode = qRcodeKey.getQrcode();
                bi = QRcodeUtils.createImage(stuId+qrcode,"",false);
            }
        }
        else{
            String qrcode = MD5Utils.md5(""+stuId+new Random().nextInt(999));
            bi =  QRcodeUtils.createImage(stuId+qrcode,"",false);
            qRcodeService.insert(new QRcodeKey(stuId,qrcode,new Date().getTime()));
        }

        ImageIO.write(bi, "JPEG", response.getOutputStream());
    }

}
